package mdt.action;

import org.tigris.gef.base.Diagram;
import org.tigris.gef.base.Editor;
import org.tigris.gef.base.Globals;
import org.tigris.gef.graph.presentation.JGraph;
import mdt.program.Displayer;
import mdt.program.GraphManager;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.*;

/**
 * Created by lambert on 2016/6/20.
 */
public class OpenAction extends AbstractAction{

	private static final long serialVersionUID = 1L;

	public OpenAction() {
		super("Open");
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			Editor ce = Globals.curEditor();
			JFileChooser chooser = new JFileChooser(GraphManager.getLastVisitedDir());
			chooser.setFileFilter(new FileFilter() {
				@Override
				public boolean accept(File f) {
					if (f.isDirectory()) return true;
					if (f.getName().toLowerCase().endsWith(".mdt")) return true;
					return false;
				}

				@Override
				public String getDescription() {
					return "MDT files(*.mdt)";
				}
			});
			File file = null;
			do {

				int result = chooser.showOpenDialog(Displayer.instance().getJFrame());
				if (result != JFileChooser.APPROVE_OPTION) {
					return;
				}

				file = chooser.getSelectedFile();
				if (file.exists()) break;
				if (!file.exists() && !file.getName().toLowerCase().endsWith(".mdt")) {
					file = new File(file.getParent(), file.getName() + ".mdt");
					if (file.exists()) break;
				}
			} while (true);
			GraphManager.setLastVisitedDir(file.getParentFile().getAbsolutePath());
			GraphManager.GraphInfo info = GraphManager.getGraphByFile(file);
			if (info != null) {
				Displayer.instance().selectTab(info.graph);
			} else {
				Globals.showStatus("Reading " + file.getAbsolutePath() + "...");
				FileInputStream fis = new FileInputStream(file);
				ObjectInput s = new ObjectInputStream(fis);
				Diagram diagram = (Diagram) s.readObject();
				if (fis != null) {
					fis.close();
				}
				Globals.showStatus("Read " + file.getAbsolutePath());
				JGraph graph = new JGraph(diagram);
				GraphManager.addGraph(graph, diagram, file.getName(), file);
				Displayer.instance().selectTab(graph);
			}

		} catch (FileNotFoundException ignore) {
			System.out.println("got an FileNotFoundException");
		} catch (java.lang.ClassNotFoundException ignore) {
			System.out.println("got an ClassNotFoundException");
		} catch (IOException ignore) {
			System.out.println("got an IOException");
		}

	}
} /* end class CmdOpen */
